package greedy;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @ Author     ：侯耀祖
 * @ Description：
 */
public class merge {
    public int[][] merge(int[][] intervals) {
        LinkedList<int[]> result = new LinkedList<>();
        Arrays.sort(intervals, (a, b) -> {
            if (a[0] == b[0]) return a[1] - b[1];
            return a[0] - b[0];
        });
        result.add(intervals[0]);
        for (int i = 1; i < intervals.length; i++) {
            int[] point = intervals[i];
            int[] pre =result.getLast();
            if (point[0] <= pre[1]){
                int[] last = result.removeLast();
                last[1] = Math.max(point[1], pre[1]);
                result.addLast(last);
            } else {
                result.addLast(point);
            }
        }
        return result.toArray(new int[result.size()][]);
    }
}
